package juc;

import sun.awt.image.ImageWatched;

import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created with IDEA
 * author:ju bai
 * Date:2021/5/30
 * Time:9:22
 * 信号量示例
 **/
public class Demo1 {
    public static void main(String[] args) {
        //创建信号量
        Semaphore semaphore = new Semaphore(2);
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                10,10,0, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(100)
        );

        //创建4辆车
        for (int i = 1; i < 5; i++) {

            //创建任务1
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + "到达停车场");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //试图进入停车场
                    try {
                        //尝试获取锁
                        semaphore.acquire();

                        //执行到这，说明已经获取到锁了
                        System.out.println(Thread.currentThread().getName() + "进入停车场-------");

                        //创建随机数代表停车时间
                        int num = 1 + new Random().nextInt(5);//1+0~5--->1~5
                        try {
                            Thread.sleep(num * 1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        //离开停车场
                        System.out.println(Thread.currentThread().getName() + "离开停车场.......");

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }finally {

                        //释放锁
                        semaphore.release();
                    }

                }
            });
        }
    }
}
